<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="机加工序" prop="dictMachiningProcess">
        <el-select v-model="formData.dictMachiningProcess" placeholder="请选择机加工序">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MACHINING_PROCESS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="零件名称" prop="partsName">
        <el-input v-model="formData.partsName" placeholder="请输入零件名称" />
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input v-model="formData.specification" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="加工工序" prop="processing">
        <el-input v-model="formData.processing" placeholder="请输入加工工序" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="formData.unit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="单价（元）" prop="unitPrice">
        <el-input v-model="formData.unitPrice" placeholder="请输入单价" @input="validateInput"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type='textarea' />
      </el-form-item>
      <el-form-item label="状态" prop="dictEnableStatus">
        <el-select v-model="formData.dictEnableStatus" placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as WageMachiningUnitPriceApi from '@/api/config/wageMachiningUnitPrice'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  dictMachiningProcess: undefined,
  partsName: undefined,
  unit: undefined,
  unitPrice: undefined,
  dictEnableStatus: undefined,
  remark: undefined,
  specification: undefined,
  processing: undefined

})
const formRules = reactive({
  dictMachiningProcess: [{ required: true, message: '机加工序不能为空', trigger: 'change' }],
  partsName: [{ required: true, message: '零件名称不能为空', trigger: 'blur' }],
  unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
  dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type,id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WageMachiningUnitPriceApi.getWageMachiningUnitPrice(id)
    } finally {
      formLoading.value = false
    }
  }else{
     formData.value.dictEnableStatus=10  
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 只能填写数字，允许小数点后 4位数
const validateInput = () => {
      // 使用正则表达式来限制输入只能为数字和最多4位小数
      formData.value.unitPrice =  formData.value.unitPrice.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
      const decimalParts =  formData.value.unitPrice.split('.');
      
      if (decimalParts.length > 2) {
  // 如果小数点出现多次，只保留第一个小数点之前的部分和小数点后的部分
      formData.value.unitPrice = decimalParts[0] + '.' + decimalParts[1];
    } else if (decimalParts[1] && decimalParts[1].length > 4) {
  // 如果小数部分超过2位，不允许继续输入
      formData.value.unitPrice = decimalParts[0] + '.' + decimalParts[1].slice(0, 4);
    }
    };



/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    data.unitPrice =Number(formData.value.unitPrice)
    if (formType.value === 'create') {
      await WageMachiningUnitPriceApi.createWageMachiningUnitPrice(data)
      message.success(t('common.createSuccess'))
    } else {
      await WageMachiningUnitPriceApi.updateWageMachiningUnitPrice(data)
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dictMachiningProcess: undefined,
    partsName: undefined,
    unit: undefined,
    unitPrice: undefined,
    dictEnableStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>
